<template>
    <div class="container" style="background-color: #E9EFFC;">
        <div class="statistics-container">
            <div class="statisticsTitle">数据总览</div>
            <el-row :gutter="20">
                <el-col :span="4">
                    <div class="statistic-card">
                        <div class="statistic-content">
                            <div class="statistic-img">
                                <img class="img-size-7" src="@/assets/images/order.png" alt="订单">
                            </div>
                            <el-statistic :value="totalMaterialValue">
                                <template #title>
                                    <div class="statisticSizs">
                                        物料总数量
                                    </div>
                                </template>
                            </el-statistic>
                        </div>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="statistic-card">
                        <div class="statistic-content">
                            <div class="statistic-img">
                                <img class="img-size-6" src="@/assets/images/abnormal.png" alt="异常">
                            </div>
                            <el-statistic class="abnormal" :value="abnormalCountValue">
                                <template #title>
                                    <div class="statisticSizs" style="display: inline-flex; align-items: center">
                                        累计异常数量
                                    </div>
                                </template>
                            </el-statistic>
                        </div>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="statistic-card">
                        <div class="statistic-content">
                            <div class="statistic-img">
                                <img class="img-size-7" src="@/assets/images/repeat.png" alt="重复">
                            </div>
                            <el-statistic class="repeat" :value="repeatCountValue">
                                <template #title>
                                    <div class="statisticSizs">
                                        累计重复数量
                                    </div>
                                </template>
                            </el-statistic>
                        </div>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="statistic-card">
                        <div class="statistic-content">
                            <div class="statistic-img">
                                <img class="img-size-7" src="@/assets/images/procedure.png" alt="流程">
                            </div>
                            <el-statistic class="procedure" :value="inProcessCountValue">
                                <template #title>
                                    <div class="statisticSizs">
                                        累计流程中数量
                                    </div>
                                </template>
                            </el-statistic>
                        </div>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="statistic-card">
                        <div class="statistic-content">
                            <div class="statistic-img">
                                <img class="img-size-6-5 ml-1" src="@/assets/images/accomplish.png" alt="已完成">
                            </div>
                            <el-statistic class="accomplish" :value="completedCountValue">
                                <template #title>
                                    <div class="statisticSizs">
                                        累计已完成数量
                                    </div>
                                </template>
                            </el-statistic>
                        </div>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="statistic-card">
                        <div class="statistic-content">
                            <div class="statistic-img">
                                <img class="img-size-6-5" src="@/assets/images/rectifyCorrect.png" alt="整改">
                            </div>
                            <el-statistic class="rectifyCorrect" :value="correctionRate">
                                <template #title>
                                    <div class="statisticSizs">
                                        问题整改完成率
                                    </div>
                                </template>
                            </el-statistic>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>
        <el-row style="background-color: #fff;">
            <el-col :span="12">
                <div>
                    <div class="chartTiTle">物料问题原因</div>
                    <div class="chartImage"><img class="chartImg" src="@/assets/images/droplet.png" alt="" /></div>
                </div>
                <div ref="questionPieChart" class="chart-item"></div>
            </el-col>
            <el-col :span="12">
                <div>
                    <div class="chartTiTle">物料问题趋势</div>
                    <div class="chartImage"><img class="chartImg" src="@/assets/images/droplet.png" alt="" /></div>
                    <div class="chartRadio">
                        <xcmg-radio-group v-model="radio" text-color="#0158F0" fill="#fff" theme="light">
                            <el-radio-button label="年" />
                            <el-radio-button label="月" />
                            <el-radio-button label="日" />
                        </xcmg-radio-group>
                    </div>
                </div>
                <div ref="lineChart" class="chart-item"></div>

            </el-col>
        </el-row>
        <el-row class="row-margin-top" style="background-color: #fff;">
            <el-col :span="12">
                <div>
                    <div class="chartTiTle">物料类型分布</div>
                    <div class="chartImage"><img class="chartImg" src="@/assets/images/droplet.png" alt="" /></div>
                </div>
                <div ref="typePieChart" class="chart-item">
                </div>
            </el-col>
            <el-col :span="12">
                <div>
                    <div class="chartTiTle">昨日物料校验结果</div>
                    <div class="chartImage"><img class="chartImg" src="@/assets/images/droplet.png" alt="" /></div>
                </div>
                <div ref="barChart" class="chart-item chart-item-padding">
                </div>
            </el-col>
        </el-row>
        <el-row class="row-margin-top" style="background-color: #fff;">
            <el-col :span="24">
                <div>
                    <div class="chartTiTle">各公司异常物料统计</div>
                    <div class="chartImage"><img class="chartImg" src="@/assets/images/droplet.png" alt="" /></div>
                </div>
                <div ref="companyBarChart" class="chart-item chart-item-padding">
                </div>
            </el-col>
        </el-row>
    </div>
</template>
  
<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch, reactive } from 'vue';
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';
import { totalCountGraph, questionClassificationGraph, materialTypeGraph, questionTrend, verificationResult, companyAbnormalGraph } from '@/api/materialQualityTest';
import { ElLoading, ElMessage } from 'element-plus';
import { Loading, Warning } from '@element-plus/icons-vue';
import { useTransition } from '@vueuse/core'

const router = useRouter();

// 数据定义
const questionPieChartData = ref([]);
const materialTypeChartData = ref([]);
const lineChartData = ref({
    xData: [],
    seriesData: []
});
const barChartData = ref({
    xData: [],
    seriesData: []
});

// 各公司异常物料统计数据
const companyChartData = ref({
    xData: [],
    seriesData: []
});

const totalMaterial = ref(0)
const abnormalCount = ref(0)
const repeatCount = ref(0)
const inProcessCount = ref(0)
const completedCount = ref(0)
const correctionRate = ref(0)


// 使用useTransition创建平滑过渡效果
const totalMaterialValue = useTransition(totalMaterial, {
    duration: 1500
});

const abnormalCountValue = useTransition(abnormalCount, {
    duration: 1500
});

const repeatCountValue = useTransition(repeatCount, {
    duration: 1500
});

const inProcessCountValue = useTransition(inProcessCount, {
    duration: 1500
});

const completedCountValue = useTransition(completedCount, {
    duration: 1500
});

const radio = ref('年');

// 图表实例引用
const questionPieChart = ref<HTMLElement | null>(null);
const lineChart = ref<HTMLElement | null>(null);
const barChart = ref<HTMLElement | null>(null);
const typePieChart = ref<HTMLElement | null>(null);
const companyBarChart = ref<HTMLElement | null>(null);


let questionPieChartInstance: echarts.ECharts | null = null;
let lineChartInstance: echarts.ECharts | null = null;
let barChartInstance: echarts.ECharts | null = null;
let typePieChartInstance: echarts.ECharts | null = null;
let companyBarChartInstance: echarts.ECharts | null = null;


// 响应式调整图表尺寸
const resizeCharts = () => {
    questionPieChartInstance?.resize();
    typePieChartInstance?.resize();
    barChartInstance?.resize();
    lineChartInstance?.resize();
    companyBarChartInstance?.resize(); // 添加公司图表调整
};
// 统计数据调用
const totalCountGraphData = async () => {
    try {
        const res = await totalCountGraph({});
        if (res.data && res.data.length >= 6) {
            totalMaterial.value = Number(res.data[0].value);
            abnormalCount.value = Number(res.data[1].value);
            repeatCount.value = Number(res.data[2].value);
            inProcessCount.value = Number(res.data[3].value);
            completedCount.value = Number(res.data[4].value);
            correctionRate.value = res.data[5].value;
        }
    } catch (error) {
        console.error('获取统计数据失败:', error);
        ElMessage.error('统计数据加载失败');
    }
};

//问题分类数据
const questionClassificationGraphData = async () => {
    try {
        const res = await questionClassificationGraph({});
        questionPieChartData.value = res.data
        updateQuestionPieChart();
    } catch (error) {
        console.error('获取问题分类数据失败:', error);
        ElMessage.error('问题分类数据加载失败');
    }
};

//问题趋势数据
const questionTrendData = async () => {
    try {
        const res = await questionTrend({
            dateType: radio.value === '年' ? 'year' : radio.value === '月' ? 'month' : 'day'
        });

        if (res.data && Array.isArray(res.data)) {
            lineChartData.value.xData = res.data.map(item => item.name);
            lineChartData.value.seriesData = res.data.map(item => Number(item.value) || 0);
        }
        updateLineChart();
    } catch (error) {
        console.error('获取问题趋势数据失败:', error);
        ElMessage.error('问题趋势数据加载失败');
    }
};

//物料类型数据
const fetchMaterialTypeData = async () => {

    try {
        const res = await materialTypeGraph({});
        materialTypeChartData.value = res.data.map(item => ({
            name: item.name,
            value: Number(item.value)
        }));
        updateTypePieChart();
    } catch (error) {
        console.error('获取物料类型数据失败:', error);
        ElMessage.error('物料类型数据加载失败');
    }
};

//物料检验结果
const verificationResultData = async () => {

    try {
        const res = await verificationResult({});

        if (res.data && Array.isArray(res.data)) {
            barChartData.value.xData = res.data.map(item => item.name);
            barChartData.value.seriesData = res.data.map(item => Number(item.value) || 0);
        }

        updateBarChart();
    } catch (error) {
        console.error('获取物料检验结果失败:', error);
        ElMessage.error('物料检验结果加载失败');
    }
};

// 获取各公司异常物料数据
const fetchCompanyAbnormalData = async () => {

    try {
        // 假设有对应的API接口
        const res = await verificationResult({});

        if (res.data && Array.isArray(res.data)) {
            companyChartData.value.xData = res.data.map(item => item.name);
            companyChartData.value.seriesData = res.data.map(item => Number(item.value) || 0);
        }

        updateCompanyBarChart();
    } catch (error) {
        console.error('获取各公司异常物料数据失败:', error);
        ElMessage.error('各公司异常物料数据加载失败');
    }
};

// 饼图点击事件
const handlePieChartClick = (params: any) => {
    router.push({
        path: '/qualityTestTable',
        query: {
            type: params.name,
            value: params.value
        }
    });
};

// 初始化问题饼图
const initQuestionPieChart = () => {
    if (!questionPieChart.value) return;

    questionPieChartInstance = echarts.init(questionPieChart.value);
    updateQuestionPieChart();
    questionPieChartInstance.on('click', handlePieChartClick);
};

// 更新问题饼图数据
const updateQuestionPieChart = () => {
    if (!questionPieChartInstance) return;

    questionPieChartInstance.setOption({
        // title: {
        //     text: '物料问题原因',
        //     left: 20,
        // },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            bottom: 20,
        },
        series: [
            {
                name: '问题类型',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    // 修改formatter来显示名称和数值
                    formatter: '{b}\n{c} ({d}%)',
                    show: true, // 设置为true以显示标签
                    position: 'outside' // 将标签放置于扇区外部

                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 18,
                        fontWeight: 'bold'
                    }
                },
                // 显示连接标签和扇区的线
                labelLine: {
                    show: true
                },
                data: [
                    { value: 1048, name: 'Search Engine' },
                    { value: 735, name: 'Direct' },
                    { value: 580, name: 'Email' },
                    { value: 484, name: 'Union Ads' },
                    { value: 300, name: 'Video Ads' }
                ]
            }
        ]
    }, true);
};

// 初始化物料类型饼图
const initTypePieChart = () => {
    if (!typePieChart.value) return;

    typePieChartInstance = echarts.init(typePieChart.value);
    updateTypePieChart();
    // typePieChartInstance.on('click', handlePieChartClick);
};

// 物料类型饼图数据
const updateTypePieChart = () => {
    if (!typePieChartInstance) return;

    typePieChartInstance.setOption({
        // title: {
        //     text: '物料类型分布',
        //     left: 20
        // },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            right: 10,
            bottom: 20,
        },
        series: [
            {
                name: '物料类型',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    // 修改formatter来显示名称和数值
                    formatter: '{b}\n{c} ({d}%)',
                    show: true, // 设置为true以显示标签
                    position: 'outside' // 将标签放置于扇区外部

                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 18,
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: true
                },
                // data: materialTypeChartData.value
                data: [
                    { value: 1048, name: '物料描述' },
                    { value: 735, name: '物料名称' },
                    { value: 580, name: '其他基础属性' },
                    { value: 484, name: '分类属性' },
                ]
            }
        ]
    }, true);
};

// 初始化折线图
const initLineChart = () => {
    if (!lineChart.value) return;

    lineChartInstance = echarts.init(lineChart.value);
    updateLineChart();
};

// 更新折线图数据
const updateLineChart = () => {
    if (!lineChartInstance) return;

    lineChartInstance.setOption({
        // title: {
        //     text: `物料问题趋势`,
        //     top: 0,
        //     left: 20
        // },
        tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>{a}: {c}'
        },
        xAxis: {
            type: 'category',
            data: lineChartData.value.xData
        },
        yAxis: {
            type: 'value',
            // name: '问题数量'
        },
        series: [{
            name: '问题数量',
            data: lineChartData.value.seriesData,
            type: 'line',
            smooth: true,
            lineStyle: {
                color: '#5470C6',
                width: 3
            },
            itemStyle: {
                color: '#5470C6'
            },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0,
                        color: 'rgba(84, 112, 198, 0.3)'
                    }, {
                        offset: 1,
                        color: 'rgba(84, 112, 198, 0.1)'
                    }]
                }
            }
        }]
    }, true);
};

// 初始化柱状图
const initBarChart = () => {
    if (!barChart.value) return;

    barChartInstance = echarts.init(barChart.value);
    updateBarChart();
};

// 更新柱状图数据
const updateBarChart = () => {
    if (!barChartInstance) return;

    barChartInstance.setOption({
        // title: {
        //     text: '昨日物料校验结果',
        //     left: 20
        // },
        grid: {
            left: '5%',
            right: '5%',
            bottom: '8%',
            top: '15%'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' }
        },
        xAxis: {
            type: 'category',
            data: barChartData.value.xData,
            axisTick: { show: false },
            axisLabel: {
                color: '#7D8695',
                interval: 0,
                rotate: barChartData.value.xData.length > 5 ? 30 : 0
            },
            splitLine: { show: false },
            axisLine: { lineStyle: { color: '#00001A26' } }
        },
        yAxis: {
            type: 'value',
            axisLabel: { color: '#7D8695' },
            splitLine: {
                lineStyle: {
                    type: 'dashed',
                    color: 'rgba(0, 0, 26, 0.15)'
                }
            }
        },
        series: [{
            name: '数量',
            type: 'bar',
            data: barChartData.value.seriesData,
            barWidth: '30%',
            itemStyle: {
                // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                //     { offset: 0, color: '#0158F0' },
                //     { offset: 1, color: '#6BACFF' }
                // ])
            },
            label: {
                show: true,
                position: 'top',
                formatter: '{c}'
            }
        }]
    }, true);
};

// 初始化公司柱状图
const initCompanyBarChart = () => {
    if (!companyBarChart.value) return;

    companyBarChartInstance = echarts.init(companyBarChart.value);
    updateCompanyBarChart();
};

// 更新公司柱状图数据
const updateCompanyBarChart = () => {
    if (!companyBarChartInstance) return;

    companyBarChartInstance.setOption({
        grid: {
            left: '5%',
            right: '5%',
            bottom: '8%',
            top: '5%'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' }
        },
        xAxis: {
            type: 'category',
            // data: companyChartData.value.xData,
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
            axisTick: { show: false },
            axisLabel: {
                color: '#7D8695',
                interval: 0,
                rotate: companyChartData.value.xData.length > 5 ? 30 : 0
            },
            splitLine: { show: false },
            axisLine: { lineStyle: { color: '#00001A26' } }
        },
        yAxis: {
            type: 'value',
            barWidth: '30%',
            axisLabel: { color: '#7D8695' },
            splitLine: {
                lineStyle: {
                    type: 'dashed',
                    color: 'rgba(0, 0, 26, 0.15)'
                }
            }
        },
        series: [{
            name: '异常数量',
            type: 'bar',
            // data: companyChartData.value.seriesData,
            data: [120, 200, 150, 80, 70, 110, 130],
            barWidth: '30%',
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#FF6B6B' },
                    { offset: 1, color: '#FF9E6D' }
                ])
            },
            label: {
                show: true,
                position: 'top',
                formatter: '{c}'
            }
        }]
    }, true);
};

// 初始化所有图表和数据
const initCharts = async () => {
    // const loading = ElLoading.service({
    //     lock: true,
    //     text: '加载数据中...',
    //     background: 'rgba(0, 0, 0, 0.7)',
    // });

    try {
        await Promise.all([
            totalCountGraphData(),
            questionClassificationGraphData(),
            questionTrendData(),
            fetchMaterialTypeData(),
            verificationResultData(),
            fetchCompanyAbnormalData() // 添加公司数据获取
        ]);

        initQuestionPieChart();
        initTypePieChart();
        initLineChart();
        initBarChart();
        initCompanyBarChart();

        window.addEventListener('resize', resizeCharts);
    } catch (error) {
        console.error('初始化图表失败:', error);
        ElMessage.error('图表初始化失败');
    }
    // finally {
    //     loading.close();
    // }
};

onMounted(() => {
    // 确保DOM已渲染
    setTimeout(() => {
        initCharts();
    }, 0);
});

watch(radio, () => {
    questionTrendData();
});

onUnmounted(() => {
    questionPieChartInstance?.dispose();
    typePieChartInstance?.dispose();
    barChartInstance?.dispose();
    lineChartInstance?.dispose();
    companyBarChartInstance?.dispose();

    window.removeEventListener('resize', resizeCharts);
});
</script>
  
<style lang="less" scoped>
/* 容器样式 */
.container {
    padding: 20px;
}

/* 边距样式 */
.row-margin-top {
    margin-top: 20px;
}


// .chart-item-padding {
//     padding-left: 12px;
// }

/* 图片尺寸样式 */
.img-size-7 {
    width: 50px;
    height: 50px;
}

.img-size-6 {
    width: 40px;
    height: 40px;
}

.img-size-6-5 {
    width: 50px;
    height: 50px;
}

.ml-1 {
    margin-left: 4px;
}

/* 新增统计卡片样式 */
.statistics-container {
    margin-bottom: 18px;
    background-color: #fff;

    .statisticsTitle {
        padding-top: 10px;
        margin-left: 20px;
        font-weight: bold;
        font-size: 16px;
    }

    .el-row {
        padding: 20px;
    }
}

.statistic-card {
    background-color: #F6F9FF;
    padding: 10px;
}

.statistic-content {
    display: flex;
    justify-content: center;
    height: 100%;
}

.statistic-img {
    margin-right: 4px;
    width: 54px;
    height: 54px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.statisticSizs {
    font-size: 14px
}

.el-statistic {
    --el-statistic-content-font-size: 24px;
}

:deep(.el-statistic__number) {
    font-weight: bold;
}

.chart-item {
    margin: 0 16px;
    min-width: 450px;
    min-height: 300px;
    background-color: #fff;
    position: relative;
}

.chartTiTle {
    padding-top: 16px;
    margin-left: 20px;
    font-weight: bold;
    font-size: 16px;
}

.chartImage {
    height: 16px;
}

.chartImg {
    margin-bottom: 10px;
    margin-left: 20px;
    width: 29px;
    height: 3px;
}

.chartRadio {
    z-index: 2;
    width: 140px;
    position: absolute;
    top: 20px;
    right: 20px;
}

.chart-loading,
.chart-error {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #606266;
    font-size: 14px;

    .el-icon {
        font-size: 40px;
        margin-bottom: 10px;
    }
}

.chart-error {
    color: #f56c6c;
}

/* 响应式设计：小屏幕时单列显示 */
@media (max-width: 768px) {
    .chart-item {
        width: 95%;
        height: 350px;
    }
}
</style>